//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <bsp.h>
#include <8254.h>

enum {
    Speaker_Port                = 0x61,
};

#define SPEAKER_ENABLE          0x03    // bit 0: use counter 2
                                        // bit 1: enable speaker

#define SPEAKER_FREQUENCE       1000

#define SPEAKER_LATCH   \
    ((uint16_t)((PIT_ClockRate + SPEAKER_FREQUENCE / 2) / SPEAKER_FREQUENCE))

INLINE void Delay()
{
    RTCTime startTime, endTime;

    BspGetRTCTime(&startTime);

    while (TRUE) {
        BspGetRTCTime(&endTime);

        if (startTime.uSeconds > endTime.uSeconds) endTime.uSeconds += 60;

        if (startTime.uSeconds < endTime.uSeconds) break;
    }
}

EXTERN_C void CDECL BspBeep()
{
    Outb(Control_Port,
         ControlWord_Mode3 + ControlWord_RWBytes + ControlWord_SelectCounter2);

    Outb(Counter2_Port, LOBYTE(SPEAKER_LATCH));
    Outb(Counter2_Port, HIBYTE(SPEAKER_LATCH));

    Outb(Speaker_Port, Inb(Speaker_Port) | SPEAKER_ENABLE);

    Delay();

    Outb(Speaker_Port, Inb(Speaker_Port) & ~SPEAKER_ENABLE);
}
